<?php

namespace app\admin\controller;

use app\common\BaseHelper;

use think\Db;
use think\Exception;
use think\Request;

class Policy extends Base
{

    public function __construct()
    {
        parent::__construct();
        $defaultWhere['status'] = 1;
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'title' => [
                'label'     => '标题',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'

            ],
            'categoryId' => [
                'label'     => '分类',
                'field'     => 'categoryId',
                'type'      => 'select',
                'disabled'  => false,
                'condition' => '=',
                'data' => BaseHelper::makeOptions(
                    model('category'),
                    ['c_type'=> 1],
                    ['sort'=> 'ASC'],
                    ['0' => '所有']
                )

            ],
        ];
        $this->redirect = 'admin/policy/index';
        $this->defaultOrder = 'createDate ASC';
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];
            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }
            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as &$item) {
                $item['categoryId'] = show_policyType($item['categoryId']);

            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        return parent::index();
    }

    public function add(){
        $policyType = get_policyType();
        return $this->fetch('',[
            'typeList' => $policyType
        ]);
    }

    public function addPost(Request $request){

        if($request->isPost()){
            $param = $request->param();
            if(empty($param['title']) || empty($param['categoryId'])){
                return $this->error('缺少必填字段');
            }
            Db::startTrans();
            try{
                $Policy = new \app\admin\model\Policy();
                $id = BaseHelper::getUUID();
                $Policy->id = $id;
                $Policy->title = $param['title'];
                $Policy->categoryId = $param['categoryId'];
                $Policy->imgUrl = $param['imgUrl'];
                $Policy->save();
                $Content = new \app\admin\model\Content();
                $Content->articleId = $id;
                $Content->content = $param['detail'];
                $Content->save();
                if(isset($param['fileIds']) && !empty($param['fileIds'])){
                    $this->insertFiles($param['fileIds'],$id);
                }
                Db::commit();
                return $this->success('添加成功',$this->redirect);
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('添加失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    private function insertFiles($fileIds,$relatedId){
        $File = new \app\admin\model\Files();
        if(!is_array($fileIds)){
            $res = [];
            $res[0] = $fileIds;
            $fileIds = $res;
        }
        $list = [];
        foreach ($fileIds as $v){
            array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
        }
        $File->isUpdate()->saveAll($list);
    }

    private function editFiles($fileIds,$relatedId){
        if(!is_array($fileIds)){
            $res = [];
            $res[0] = $fileIds;
            $fileIds = $res;
        }
        $FileList =  \app\admin\model\Files::where('relatedId',$relatedId)->field('id')->select();
        if($FileList){
            $alreadylist = [];
            foreach ($FileList as $v){
                array_push($alreadylist,$v['id']);
            }
            $reslist = array_diff($fileIds,$alreadylist);
            $list = [];
            if($reslist){
                foreach ($reslist as $v){
                    array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
                }
            }
        }else{
            $list = [];
            foreach ($fileIds as $v){
                array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
            }
        }
        if($list){
            $File = new \app\admin\model\Files();
            $File->isUpdate()->saveAll($list);
        }
    }

    public function edit(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $Policy = \app\admin\model\Policy::get($param['id']);
        $Policy['detail'] = \app\admin\model\Content::where('articleId',$Policy->id)->value('content');
        $policyType = get_policyType();
        $files = \app\admin\model\Files::where('relatedId',$Policy->id)->select();
        if($files){
            $this->assign('fileList',$files);
        }else{
            $this->assign('fileList',null);
        }
        return $this->fetch('',[
            'typeList' => $policyType,
            'info' => $Policy,
            ''
        ]);
    }

    public function editPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            if(empty($param['title']) || empty($param['categoryId'])){
                return $this->error('缺少必填字段');
            }
            Db::startTrans();
            try{
                $Policy = \app\admin\model\Policy::get($param['id']);
                if($Policy){
                    $Policy->title = $param['title'];
                    $Policy->categoryId = $param['categoryId'];
                    $Policy->imgUrl = $param['imgUrl'];
                    $Policy->save();
                    $Content = \app\admin\model\Content::where('articleId',$Policy->id)->find();
                    $Content->content = $param['detail'];
                    $Content->save();
                    if(isset($param['fileIds']) && !empty($param['fileIds'])){
                        $this->editFiles($param['fileIds'],$param['id']);
                    }
                    Db::commit();
                    return $this->success('修改成功',$this->redirect);
                }else{
                    return $this->error('此文章不存在');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('修改失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function detail($id){
        if(empty($id)){
            return $this->error('缺少参数');
        }
        $Policy = \app\admin\model\Policy::get($id);
        if($Policy){
            $Content = \app\admin\model\Content::where('articleId',$Policy->id)->find();
            $Policy['content'] = $Content->content;
            return $this->fetch('',[
                'info' =>$Policy
            ]);
        }else{
            return $this->error('资源不存在');
        }
    }

    //分类管理
    public function category(){
        $Category = Common::getCategory(1);

        return $this->fetch('',[
            'list' => $Category,
            'title' => '文件通知分类',
            'bcn' => '<ul class="page-breadcrumb"><li><i class="icon-home"></i>&nbsp;<a href="'.url('admin/index/index').'">首页</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<a href="'.url('admin/menu/index',['id' => 1]).'">住建</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<a href="'.url('admin/policy/index').'">文件通知</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<span>分类</span></li></ul>'
        ]);
    }

    public function saveCategory(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['name']) || empty($param['c_type'])){
                return $this->error('缺少参数');
            }

            if(!empty($param['id']) && $param['id']){
                $Category = \app\admin\model\Category::get($param['id']);
            }else{
                $Category = new \app\admin\model\Category();
            }

            $Category->name = $param['name'];
            $Category->c_type = $param['c_type'];
            $Category->sort = $param['sort']?$param['sort']:1;
            if($Category->save()){
                return $this->success('ok');
            }else{
                return $this->error('保存失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }


    public function delCategory(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            $Policy = \app\admin\model\Policy::where(['categoryId'=>$param['id'],'status'=>1])->find();
            if($Policy){
                return $this->error('该分类下有文章，不能删除');
            }else{
                $Category = \app\admin\model\Category::get($param['id']);
                if($Category){
                    $Category->delete();
                    return $this->success('ok');
                }else{
                    return $this->error('删除失败');
                }
            }



        }else{
            return $this->error('非法请求');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
            if(isset($filter['categoryId']) && $filter['categoryId']){
                $where['categoryId'] = $filter['categoryId'];
            }
        }

        return $where;
    }
}